package com.tenbent.product.base.security.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tenbent.product.base.security.CustomAuthenticationFailureHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

/**
 * 自定义认证失败处理类
 *
 * 此功能类似于(formLogin().loginPage("/login").failureUrl("/login?error"))
 *
 * 所做的事情，也算是一种扩展
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/6/16.
 */
public class CustomAuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler
		implements CustomAuthenticationFailureHandler {

	private String defaultUrl = "/login?error";

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		// Todo 根据需求写自己业务代码，如果只是跳转统一页面则配置上使用 .failureUrl("/login?error")代替此类
		if (response.isCommitted()) {
			System.out.println("Can't redirect");
			return;
		}
		redirectStrategy.sendRedirect(request, response, defaultUrl + "=" + exception.getMessage());
	}
}
